package com.lsl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsl.entity.Blog;
import com.lsl.entity.Result;
import com.lsl.service.BlogService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/blog-service")
public class RandomBlogController {

    @Autowired
    private BlogService blogService;

    private final Random random = new Random();

    @GetMapping("/pickBlog")
    public Result<Blog> pickRandomBlog() {
        // 获取所有博客ID列表
        List<Long> blogIds = blogService.listObjs(
            new LambdaQueryWrapper<Blog>()
                .select(Blog::getId),
            obj -> Long.valueOf(obj.toString())
        );

        if (blogIds.isEmpty()) {
            return Result.error(404, "当前没有漂流瓶可供选择");
        }

        // 随机选择一个ID
        Long randomId = blogIds.get(random.nextInt(blogIds.size()));

        // 查询并返回随机博客
        return Result.success(blogService.getById(randomId));
    }
}
